var WISDRAW = function(){
	var isTouchSupported = 'ontouchstart' in window;
	var isPointerSupported = navigator.pointerEnabled;
	var isMSPointerSupported =  navigator.msPointerEnabled;
	var isActive = false;
    var preTime_ = null;
	var preX_;
	var preY_;
	var downEvent = isTouchSupported ? 'touchstart' : (isPointerSupported ? 'pointerdown' : (isMSPointerSupported ? 'MSPointerDown' : 'mousedown'));
	var moveEvent = isTouchSupported ? 'touchmove' : (isPointerSupported ? 'pointermove' : (isMSPointerSupported ? 'MSPointerMove' : 'mousemove'));
	var upEvent = isTouchSupported ? 'touchend' : (isPointerSupported ? 'pointerup' : (isMSPointerSupported ? 'MSPointerUp' : 'mouseup'));
	var mouseDownEvent = (isMSPointerSupported ? 'MSPointerDown' : 'mousedown')
	var mouseMoveEvent = (isMSPointerSupported ? 'MSPointerMove' : 'mousemove')
	var mouseUpEvent = (isMSPointerSupported ? 'MSPointerUp' : 'mouseup')

	var opt_ = {

	}
	function getDrawByType(type){
    	if(type == "rect"){
    		return new rectDraw(opt_.ctx,opt_.ctxFg,opt_.syncData);
    	}else if(type == "line"){
    		return new lineDraw(opt_.ctx,opt_.ctxFg,opt_.syncData);
    	}else if(type == "custom"){
    		return new customDraw(opt_.ctx,opt_.ctxFg,opt_.syncData);
    	}else if(type == "clear"){
    		return new clearDraw(opt_.ctx,opt_.ctxFg,opt_.syncData);
    	}else if(type == "text"){
    		return new textDraw(opt_.ctx,opt_.ctxFg,opt_.syncData);
    	}else{
    		return null
    	}
    }
	var inherits = function(ctor, superCtor) {
	  ctor.super_ = superCtor;
	  ctor.prototype = Object.create(superCtor.prototype, {
	    constructor: {
	      value: ctor,
	      enumerable: false,
	      writable: true,
	      configurable: true
	    }
	  });
	};
	function baseDraw( ctx,ctxFg ,puber){
		this.ctx_ = ctx;
		this.ctxFg_ = ctxFg;
		this.lineWidth_ = 1;
		this.color_ = "red";
		this.sp_;
		this.ep_;
		this.puber_ = puber;
		this.fontSize_ = 20;
	}
	baseDraw.prototype.recvDraw = function(message){
		this.LineWidth(message.lw);
		this.Color(message.color);
		this.Draw(message.start,message.end);
	}
	baseDraw.prototype.Start = function(x,y){
		this.sp_ = {x:x,y:y}
	}
	baseDraw.prototype.Move = function (x,y){
		this.clearFg();
		this.ep_ = {x:x,y:y}
		this.DrawFg(this.sp_,this.ep_);
	}
	baseDraw.prototype.End = function (x,y){
		this.clearFg();
		this.ep_ = {x:x,y:y}
		this.Draw(this.sp_,this.ep_);
		this.Sync();
	}
	baseDraw.prototype.Click = function(){

	}
	baseDraw.prototype.KeyEnter = function(){

	}
	baseDraw.prototype.initDrawEvent= function(allowDraw){

		if(allowDraw){
			if(isTouchSupported){
				opt_.div.addEventListener(mouseDownEvent, startDraw, false);
				opt_.div.addEventListener(mouseMoveEvent, drawing, false);
				opt_.div.addEventListener(mouseUpEvent, endDraw, false);
			}
			opt_.div.addEventListener(downEvent, startDraw, false);
			opt_.div.addEventListener(moveEvent, drawing, false);
			opt_.div.addEventListener(upEvent, endDraw, false);
		}else{
			if(isTouchSupported){
				opt_.div.removeEventListener(mouseDownEvent, startDraw, false);
				opt_.div.removeEventListener(mouseMoveEvent, drawing, false);
				opt_.div.removeEventListener(mouseUpEvent, endDraw, false);
			}
			opt_.div.removeEventListener(downEvent, startDraw, false);
			opt_.div.removeEventListener(moveEvent, drawing, false);
			opt_.div.removeEventListener(upEvent, endDraw, false);
		}
	}
	baseDraw.prototype.Sync=function(){
		this.puber_({
	  		cmd:"draw",
	  		type:this.Type(),
	  		lw:this.LineWidth(),
	  		color: this.Color(),
	  		start:this.StartPoint(),
	  		end:this.EndPoint()
	  	});
	}
	baseDraw.prototype.clearFg = function(){
		this.ctxFg_.clearRect(0,0,opt_.canvasFg.width,opt_.canvasFg.height);
	}
	baseDraw.prototype.FontSize = function(fs){
		if(Number(fs) > 0)
			this.fontSize_ = fs
		return this.fontSize_;
	}
	baseDraw.prototype.Release = function(){

	}
	baseDraw.prototype.Color = function(color){
		if(color!=null)
			this.color_ = color
		return this.color_;
	}
	baseDraw.prototype.StartPoint = function(){
		return this.sp_;
	}
	baseDraw.prototype.EndPoint = function(){
		return this.ep_;
	}
	baseDraw.prototype.LineWidth = function (w ){
		if(w!=null)
			this.lineWidth_ = w
		return this.lineWidth_;
	}
	function lineDraw( ctx ,ctxFg,puber){
		baseDraw.call(this,ctx,ctxFg,puber);
	}
	inherits(lineDraw,baseDraw)
	lineDraw.prototype.Type = function(){
		return 'line';
	}
	lineDraw.prototype.DrawFg = function(startPoint,endPoint){
		/*this.ctxFg_.lineWidth = this.lineWidth_;
		this.ctxFg_.strokeStyle= this.color_;//轮廓颜色
		this.ctxFg_.beginPath();   
        this.ctxFg_.moveTo(startPoint.x,startPoint.y);   
        this.ctxFg_.lineTo(endPoint.x,endPoint.y);   
        this.ctxFg_.stroke();*/
	}

	lineDraw.prototype.Draw = function(startPoint,endPoint){
		this.ctx_.lineWidth = this.lineWidth_;
		this.ctx_.strokeStyle= this.color_;//轮廓颜色
		this.ctx_.beginPath();   
        this.ctx_.moveTo(startPoint.x,startPoint.y);   
        this.ctx_.lineTo(endPoint.x,endPoint.y);   
        this.ctx_.stroke();
	}
	function rectDraw( ctx,ctxFg ,puber){
		baseDraw.call(this,ctx,ctxFg,puber);
	}
	inherits(rectDraw,baseDraw)
	rectDraw.prototype.Type = function(){
		return 'rect';
	}
	rectDraw.prototype.Draw = function(startPoint,endPoint){
		if(!endPoint || !startPoint) return;
		this.ctx_.lineWidth = this.lineWidth_;
		this.ctx_.strokeStyle= this.color_;//轮廓颜色
		this.ctx_.strokeRect(startPoint.x,startPoint.y,endPoint.x-startPoint.x,endPoint.y-startPoint.y);
	}
	rectDraw.prototype.DrawFg = function(startPoint,endPoint){
		if(!endPoint || !startPoint) return;
		this.ctxFg_.lineWidth = this.lineWidth_;
		this.ctxFg_.strokeStyle= this.color_;//轮廓颜色
		this.ctxFg_.strokeRect(startPoint.x,startPoint.y,endPoint.x-startPoint.x,endPoint.y-startPoint.y);
	}
	function customDraw( ctx ,ctxFg,puber){
		baseDraw.call(this,ctx,ctxFg,puber);
		this.polts_ = [];
		this.s = null;
	}
	inherits(customDraw,baseDraw)
	customDraw.prototype.Type = function(){
		return 'custom';
	}
	customDraw.prototype.Start = function(x,y){
		this.polts_.push( x,y );
		this.s = {x:x,y:y}
	}
	customDraw.prototype.Move = function (x,y){
		if(this.polts_.length > 2 && x == this.polts_[this.polts_.length - 2] && y == this.polts_[this.polts_.length - 1]){
			console.log('drop');
			return;
		}
		if(!this.isBig())this.polts_.push( x,y );
		this.Draw([this.s.x,this.s.y,x,y]);
		this.s = {x:x,y:y}
	}
	customDraw.prototype.End = function (x,y){
		if(!this.isBig())this.polts_.push( x,y );
		this.Draw([this.s.x,this.s.y,x,y]);
		this.s = {x:x,y:y}
		this.Sync();
		
	}
	customDraw.prototype.Draw = function(plots){
		this.ctx_.lineWidth = this.lineWidth_;
		this.ctx_.strokeStyle= this.color_;//轮廓颜色
		this.ctx_.beginPath();
		this.ctx_.moveTo(plots[0], plots[1]);
    	for(var i=1; i<plots.length/2; i++) {
	    	this.ctx_.lineTo(plots[2*i], plots[2*i+1]);
	    }
	    this.ctx_.stroke();
	}
	customDraw.prototype.recvDraw = function(message){
		this.LineWidth(message.lw);
		this.Color(message.color);
		this.Draw(message.plots);
	}
	customDraw.prototype.isBig = function(){
		if(JSON.stringify(this.polts_).length > 850){
	  		return true;
	  	}
	  	return false;
	}
	customDraw.prototype.Sync=function(){
		var obj = {
	  		cmd:"draw",
	  		type:this.Type(),
	  		lw:this.LineWidth(),
	  		color: this.Color(),
	  		plots:this.polts_
	  	};
		this.puber_(obj);
	  	this.polts_ = [];
	}
	function clearDraw( ctx ,ctxFg,puber){
		baseDraw.call(this,ctx,ctxFg,puber);
	}
	inherits(clearDraw,baseDraw)
	clearDraw.prototype.Type = function(){
		return 'clear';
	}
	clearDraw.prototype.Draw = function(start,end){
		if(start == null || end == null){
			return
		}
		this.ctx_.clearRect(start.x,start.y,end.x-start.x,end.y-start.y);
	}
	clearDraw.prototype.DrawFg = function(start,end){
		this.ctxFg_.lineWidth = 1;
		this.ctxFg_.strokeStyle= "red";//轮廓颜色
		this.ctxFg_.strokeRect(start.x,start.y,end.x-start.x,end.y-start.y);
	}
	clearDraw.prototype.Sync=function(){
		this.puber_({
	  		cmd:"draw",
	  		type:this.Type(),
	  		lw:this.LineWidth(),
	  		color: this.Color(),
	  		start:this.StartPoint(),
	  		end:this.EndPoint()
	  	});
	}
	function textDraw( ctx ,ctxFg,puber){
		baseDraw.call(this,ctx,ctxFg,puber);
		
	}
	inherits(textDraw,baseDraw)
	textDraw.prototype.Type = function(){
		return 'text';
	}
	textDraw.prototype.Start = function(x,y){
	}
	textDraw.prototype.Move = function (x,y){
	}
	textDraw.prototype.End = function (x,y){	
	}
	textDraw.prototype.Draw = function(fz,text,point,color){
		this.ctx_.font=fz+"px Microsoft YaHei";
		this.ctx_.fillStyle = color;
		this.ctx_.fillText(text,point.x,point.y);
		
	}
	textDraw.prototype.recvDraw = function(message){
		this.Draw(message.fs,message.text,message.start,message.color);
	}
	textDraw.prototype.Click = function(x,y,e){
		if(e.target != opt_.div) return;	
		this.sp_ = {x:x,y:y}
		if(!this.input_){
			this.input_ = document.createElement("input");
			this.input_.style.marginTop = y+"px";
			this.input_.style.marginLeft = x+"px";
			this.input_.style.width = (opt_.div.width - x -10)+"px";
		}else{
			opt_.div.removeChild(this.input_);
			this.input_.style.marginTop = y+"px";
			this.input_.style.marginLeft = x+"px";
			this.input_.style.width = (opt_.div.width - x -10 )+"px";
		}
		this.input_.maxLength = 50;
		this.input_.style.backgroundColor = "transparent";
		this.input_.style.color = this.Color();
		this.input_.style.font = this.fontSize_ + "px Microsoft YaHei";
		opt_.div.appendChild(this.input_);
	}
	textDraw.prototype.initDrawEvent= function(allowDraw){
		if(allowDraw){
			opt_.div.addEventListener("click", onClick, false);
			opt_.div.addEventListener("keydown",onKeyDown,false);
		}else{
			opt_.div.removeEventListener("keydown",onKeyDown,false);
			opt_.div.removeEventListener("click", onClick, false);
		}
	}
	textDraw.prototype.KeyEnter = function(){
		this.text_ = (this.input_.value);	
		opt_.div.removeChild(this.input_);
		this.input_ = null;
		if(this.text_ != "" && this.text_!= null){
			this.sp_.y += this.fontSize_;
			this.Draw(this.fontSize_,this.text_,this.sp_,this.Color());
			this.Sync();
		}
		
	}
	textDraw.prototype.Sync=function(){
		var obj = {
	  		cmd:"draw",
	  		type:this.Type(),
	  		text:this.text_,
	  		start:this.sp_,
	  		fs:this.fontSize_,
	  		color: this.Color(),
	  	};
		this.puber_(obj);
	  	this.text_ = '';
	}
	textDraw.prototype.Release = function(){
		if(this.input_){
			opt_.div.removeChild(this.input_);
		}
	}
	function drawing(e) {
		if(!opt_.allowDraw) return;
		e.stopPropagation();
		e.preventDefault(); 

	  	if(!isActive) return;
	  	var now =  new Date().getTime();
	  	if(now-preTime_ < 10){
	  		return;
	  	}
	  	preTime_ = now;
		var x = e.targetTouches ? (e.targetTouches[0].pageX - opt_.canvas.offsetLeft) : (e.offsetX || e.layerX);
    	var y = e.targetTouches ? (e.targetTouches[0].pageY - opt_.canvas.offsetTop) : (e.offsetY || e.layerY);
    	curDraw_.Move(x<< 0,y<< 0);
    	preX_ = x;
    	preY_ = y;
	}

	function startDraw(e) {
		if(!opt_.allowDraw) return;
		e.stopPropagation();
		e.preventDefault(); 

	  	isActive = true;
	  	preTime_ = new Date().getTime();
	  	var x = e.targetTouches ? (e.targetTouches[0].pageX - opt_.canvas.offsetLeft) : (e.offsetX || e.layerX);
    	var y = e.targetTouches ? (e.targetTouches[0].pageY - opt_.canvas.offsetTop) : (e.offsetY || e.layerY);
    	curDraw_.Start(x<< 0,y<< 0);
    	preX_ = x;
    	preY_ = y;
	}
	function endDraw(e) {
		if(!opt_.allowDraw) return;
		e.stopPropagation();
		e.preventDefault(); 
		if(!isActive) return;
		isActive = false;
		if(e.targetTouches && e.targetTouches.length ==0){
			var x = preX_;
			var y = preY_;
		}else{
			var x = e.targetTouches ? (e.targetTouches[0].pageX - opt_.canvas.offsetLeft) : (e.offsetX || e.layerX);
	   	 	var y = e.targetTouches ? (e.targetTouches[0].pageY - opt_.canvas.offsetTop) : (e.offsetY || e.layerY);
		}
		curDraw_.End(x<< 0,y<< 0);
	}
	function onClick(e){
		if(!opt_.allowDraw) return;
		var x = e.targetTouches ? (e.targetTouches[0].pageX - opt_.canvas.offsetLeft) : (e.offsetX || e.layerX);
   	 	var y = e.targetTouches ? (e.targetTouches[0].pageY - opt_.canvas.offsetTop) : (e.offsetY || e.layerY);
   	 	curDraw_.Click(x<< 0,y<< 0,e);
	}
	function onKeyDown(e){
		if(!opt_.allowDraw) return;
		if (e == null || e.keyCode == null || e.ctrlKey == null) return;
        if (e.keyCode == 13 ) {
            e.preventDefault();
           	curDraw_.KeyEnter();
        }
	}
	var curDraw_ = null;

	return {
		Init:function(canvas,canvasFg,syncData,bgImg,div){
			opt_.allowDraw = false;
			opt_.bgImg = bgImg;
			opt_.canvas = canvas;
			opt_.div = div;
			opt_.canvasFg = canvasFg;
			opt_.ctxFg = opt_.canvasFg.getContext('2d');
			opt_.ctx = opt_.canvas.getContext('2d');
			opt_.ctx.lineCap = opt_.ctx.lineJoin = 'round';
			opt_.ctxFg.lineCap = opt_.ctxFg.lineJoin = 'round';
			opt_.syncData = syncData;
			
			curDraw_ = getDrawByType("custom");
			curDraw_.Color("#B22222");
			curDraw_.LineWidth(1);
		},
		LineWidth:function(lw){
			return curDraw_.LineWidth(lw);
		},
		Clear:function(){
			opt_.ctx.clearRect(0,0,opt_.canvas.width,opt_.canvas.height);
		},
		Color:function(co){
			if (co.indexOf("#") < 0){
				throw new Error("color format error")
			}
			return curDraw_.Color(co);
		},
		FontSize:function(fs){
			if (! Number(fs)){
				throw new Error("FontSize format error")
			}
			return curDraw_.FontSize(fs);
		},
		SetDrawType:function(type,option){
			var r= getDrawByType(type,option);
			if(r!=null){
				if(curDraw_){
					curDraw_.initDrawEvent(false);
					r.Color(curDraw_.Color());
					r.LineWidth(curDraw_.LineWidth());
					curDraw_.Release();
				}
				curDraw_ = r;
				r.initDrawEvent(opt_.allowDraw);
			}
		},
		RecvDraw:function(message){
			var r = getDrawByType(message.type)
			if(r){
				r.recvDraw(message);
			}
		},
		AllowDraw:function( val ){
			val = (!!val)
			if(opt_.allowDraw != val){
				opt_.allowDraw = val
				curDraw_.initDrawEvent(opt_.allowDraw);
			
			}
		},
		ShowBg:function(option){
			opt_.ctx.clearRect(0,0,opt_.canvas.width,opt_.canvas.height);
			var tmpPage = opt_.curPage;
			opt_.bgImg.src = option.url;
			opt_.bgImg.width = opt_.canvas.width;
			opt_.bgImg.height = opt_.canvas.height;
			opt_.bgImg.onload = function(){
				if(option.success)option.success();
			}
			opt_.bgImg.onerror =function(){
				if(option.failure)option.failure();
			}
			if(!option.pageUrl) return;
			var img=new Image();
			img.src = option.pageUrl;
			img.width = opt_.canvas.width;
			img.height = opt_.canvas.height;
			img.onload = function(){
				//if(tmpPage == opt_.curPage){
					opt_.ctx.drawImage(img,0,0,opt_.canvas.width,opt_.canvas.height);
				//}
				//if(option.success)option.success();
			}
			//img.onerror = option.failure;
		},
		Resize:function ( obj){
			opt_.bgImg.width = obj.width;
			opt_.bgImg.height = obj.height;
			opt_.canvasFg.width =opt_.canvas.width = obj.width
			opt_.canvasFg.height =opt_.canvas.height = obj.height
			opt_.div.style.width  = obj.width + "px";
			opt_.div.style.height  = obj.height + "px";
			opt_.div.width = obj.width;
			opt_.div.height = obj.height;
	    }
	}
}